﻿using Admin.CommonLib.Constants;
using Admin.RazorLib.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;
using Swimj.CommonLib.Constants;

namespace Admin.RazorLib
{
    public static class ServiceCollectionExtensions
    {
        public static void AddAdminBlazor(this IServiceCollection services)
        {
            services.AddScoped<ExampleJsInterop>();


            services.AddAuthorizationCore(options =>
            {
                RegisterPermissionClaims(options);
            });

            services.AddTransient<IAccountService, AccountService>();
            services.AddTransient<IUserService, UserService>();
            services.AddTransient<IRoleService, RoleService>();
            services.AddTransient<IPermissionService, PermissionService>();
            // services.AddTransient<IJobService, JobService>();
            services.AddTransient<IFileService, FileService>();
        }

        private static void RegisterPermissionClaims(AuthorizationOptions options)
        {
            foreach (var prop in typeof(ApiRoutes).GetNestedTypes().SelectMany(c =>
                                 c.GetFields(BindingFlags.Public | BindingFlags.Static |
                                             BindingFlags.FlattenHierarchy)))
            {
                options.AddPolicy(prop.Name,
                    policy => policy.RequireClaim(ApplicationClaimTypes.Permission,
                        prop.Name));
            }
        }
    }
}